import os
import simplejson
from django.shortcuts import render
from django.http import HttpResponse
from util.jiafu_log import JiaFuLogger

from util.const import JIAFU_CLIENT_FILE, CPS_CLIENT_FILE

# Create your views here.

logger = JiaFuLogger("jiafu_server:client_version:view")


def get_client_version(request):
    if request.method == 'GET':
        client_type = request.GET.get('client_type')
        if client_type == 'jiafu_client':
            version = _get_version(JIAFU_CLIENT_FILE)
        elif client_type == 'cps_client':
            version = _get_version(CPS_CLIENT_FILE)
        else:
            version = None
        if version:
            return HttpResponse(content=simplejson.dumps({'version': version}))
        else:
            return HttpResponse(status=404, content=simplejson.dumps({'version': 'unknown'}))


def _get_version(version_file):
    if os.path.exists(version_file):
        with open(version_file) as f:
            lines = f.readlines()
            for line in lines:
                if line:
                    version = line.strip()
                    break
        if version:
            return version
    logger.error('not found version file %s' % version_file)
    return None
